import axios from 'axios'
import { baseURL } from './config'
import { Toast, Notify } from 'vant'
import router from '@/router'

const AUTH_TOKEN = ''

axios.defaults.baseURL = baseURL // 服务接口的 基路径
axios.defaults.headers.common.Authorization = AUTH_TOKEN
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
axios.defaults.timeout = 60000

export function ShowLoading () {
  Toast.clear()
  Toast.loading({
    message: '请求中...',
    forbidClick: true
  })
}

export function ShowSuccess (msg) {
  Toast.clear()
  msg = msg || '请求成功'
  Notify({ type: 'success', message: msg })
}

export function ShowFail (msg) {
  Toast.clear()
  msg = msg || '请求失败'
  // Toast(msg)
  Notify({ type: 'danger', message: msg })
}

// 拦截器Interceptors
axios.interceptors.request.use(function (config) { // config --> 请求的参数信息  包括 body  params  query
  const server_token = window.sessionStorage.getItem('server_token')

  // axios.headers.common['_token'] = server_token;  // axios是全局设局一个token，不会改变
  config.headers.common['_token'] = server_token // 每次请求都从新设置请求头的token

  // console.log(config,111);
  ShowLoading()
  return config
}, function (error) {
  ShowFail('请求失败')
  return Promise.reject(error)
})

// 请求响应完成
axios.interceptors.response.use(function (response) {
  Toast.clear()
  // 响应成功
  console.log(response.data)
  if (response.data.code == 200) {
    // 成功
    // ShowSuccess(response.data.msg)
  } else if (response.data.code == 402 || response.data.code == 404 || response.data.code == 500 || response.data.code == 503) {
    ShowFail(response.data.msg)
  } else if (response.data.code == 3000) {
    ShowFail(response.data.msg)
    window.sessionStorage.removeItem('username')
    router.replace({ name: 'login' })
  }

  return response
}, function (error) {
  ShowFail('响应失败')
  return Promise.reject(error)
})

// get 请求
export const get = function (url, params, headers) {
  return new Promise(function (resolve, reject) {
    axios.get(url, {
      params,
      headers
    })
      .then(res => {
        resolve(res.data) // data 消除
      })
      .catch(err => {
        reject(err)
      })
  })
}

// POST  请求
export const post = function (url, body, headers, params) {
  return new Promise(function (resolve, reject) {
    axios.post(url, body, {
      params,
      headers
    })
      .then(res => {
        resolve(res.data) // data 消除
      })
      .catch(err => {
        reject(err)
      })
  })
}
